<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationBarTitleText: '待支付',
    enablePullDownRefresh: false,
  },
}
</route>
<template>
  <view class="page">
    <view class="product" v-if="goodsList.length">
      <around :showSales="false" :data="item" nameKey="goods_name" imageKey="goods_image" priceKey="goods_price"
        v-for="item in goodsList" :key="item.id">
        <!-- <view class="mt-auto">
          <discount-bar :levelName="item.levelName" :price="item.member_price" />
        </view> -->
      </around>

      <view v-if="isShowAn" class="flex justify-center items-center text-sm mt-4 text-[#9A9A9A]"
        @click="handleToggleShowAll">
        <text>{{ state.showAll ? '收起' : '展开' }}</text>
        <wd-icon :name="state.showAll ? 'arrow-up' : 'arrow-down'" size="32rpx"></wd-icon>
      </view>
    </view>

    <view class="mt-[20rpx]">
      <!-- @click="handleCellClick(k)" -->
      <view class="cell" v-for="(item, k, index) in state.buyInfo" :key="index">
        <view class="cell-left">
          <image :src="item.icon" class="w-[32rpx] h-[32rpx] mr-[11rpx]"></image>
          <text>{{ item.name }}</text>
        </view>
        <view class="cell-right">
          <text v-if="k !== 'address'">-￥{{ item.value }}</text>
          <text v-else class="text-right ml-2">{{ item.value }}</text>
          <!-- <wd-icon name="chevron-right" size="24rpx" color="var(--wot-color-theme)"></wd-icon> -->
        </view>
      </view>
    </view>

    <float-bottom>
      <view class="flex items-center justify-between px-4 h-full border-t-solid border-t-1 border-[#F2F2F2]">
        <view class="text-base text-[34rpx]">
          <text class="text-[28rpx]">￥</text>
          <text class="font-bold">{{ state.orderInfo.order_amount }}</text>
        </view>
        <view v-if="state.orderInfo.order_status == 0" class="flex-1 flex gap-x-[20rpx] ml-[50rpx]">
          <wd-button :round="false" :block="true" plain custom-class="flex-1" @click="handleCancelOrder">
            取消订单
          </wd-button>
          <wd-button :round="false" :block="true" type="primary" custom-class="flex-1" @click="handleBuy">
            立即支付
          </wd-button>
        </view>
      </view>
    </float-bottom>
  </view>
</template>

<script setup>
import { fetchCancelOrder, fetchPay, fetchOrderDetail } from '@/service/order'
import { to, toBack } from '@/utils/navigation'
import { showToast, requestPayment } from '@/utils/uni'

const state = ref({
  showAll: false,
  maxShow: 3,
  routeParams: {
    id: '',
  },
  buyInfo: {
    deduction: {
      value: 0,
      name: '积分抵扣',
      icon: '/static/images/deduction.png'
    },
    discount: {
      value: 0,
      name: '商品折扣',
      icon: '/static/images/discount.png',
    },
    coupon: {
      value: 0,
      name: '优惠券',
      icon: '/static/images/coupon.png',
    },
    address: {
      value: '',
      name: '地址',
      icon: '/static/images/address.png',
    },
  },
  orderInfo: {},
})

// 是否要显示展开
const isShowAn = computed(() => {
  return state.value.orderInfo.order_goods.length > state.value.maxShow
})

const goodsList = computed(() => {
  if (!state.value.orderInfo?.order_goods) return []
  if (state.value.showAll) return state.value.orderInfo.order_goods
  return state.value.orderInfo.order_goods.filter((item, index) => index < state.value.maxShow)
})

const payWay = computed(() => {
  // return process.env.NODE_ENV === 'development' ? 1 : 2
  return 2
})

async function handleBuy() {
  try {
    const result = await fetchPay({
      order_id: state.value.orderInfo.id,
      pay_way: payWay.value,
      from: 'order',
      order_source: 3,
    })

    if (payWay.value == 1 || result.data.is_pay) {
      showToast('支付成功', toBack)
    } else {
      requestPayment(result.data.config).then((res) => {
        showToast('支付成功', toBack)
      })
    }
  } catch (e) {
    showToast('支付失败')
  }

}
function handleCellClick(key) {
  switch (key) {
    case 'address': {
      to(`pages-sub/person/address?used=1`)
      break
    }
  }
}

function fomatAddress(address) {
  const { province, city, district } = address
  state.value.buyInfo.address = {
    ...state.value.buyInfo.address,
    ...address,
    value: `${province}${city}${district}${address.address}`,
  }
}

function getOrderInfo() {
  const { id } = state.value.routeParams
  fetchOrderDetail(id).then((res) => {
    // console.log(`详情`, res)
    const { delivery_address, member_amount, coupon_discount, integral_amount } = res.data
    state.value.orderInfo = res.data
    state.value.buyInfo.address.value = delivery_address
    state.value.buyInfo.discount.value = member_amount
    state.value.buyInfo.coupon.value = coupon_discount || 0
    state.value.buyInfo.deduction.value = integral_amount || 0
  })
}

function handleToggleShowAll() {
  state.value.showAll = !state.value.showAll
}

function handleCancelOrder() {
  uni.showModal({
    content: '确定要取消该订单吗?',
    success: (r) => {
      if (r.confirm) {
        const { id } = state.value.routeParams
        fetchCancelOrder(id).then((res) => {
          showToast(res.msg, toBack);
        })
      }
    },
  })
}

onLoad((params) => {
  state.value.routeParams = params
  getOrderInfo()
  uni.$once('usedAddress', fomatAddress)
})
</script>

<style lang="scss" scoped>
.page {
  @include addSafeArea(146rpx);
}

.product {
  @apply px-4 pt-5 pb-4;
  box-shadow: 0rpx 3rpx 10rpx 1rpx rgba(0, 0, 0, 0.1);
}

.cell {
  @apply p-4 flex justify-between items-center text-sm;
  border-bottom: 1px solid #ededed;

  &-left {
    @apply flex items-center;
    color: #9a9a9a;
  }

  &-right {
    @apply flex items-center text-base flex-1 justify-end flex-wrap;
  }
}
</style>
